package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.CommonResult;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 李红磊
 * @since 2021-06-13
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public CommonResult addVideo(@RequestBody EduVideo eduVideo){
        boolean save = eduVideoService.save(eduVideo);
        return save?CommonResult.ok():CommonResult.error();
    }


    //删除小节，同时删除小节下面的视频
    //          TODO  需要完善
    @DeleteMapping("deleteVideo/{id}")
    public CommonResult deleteVideo(@PathVariable("id")String id){//这个id是小节id。我们需要的是视频id
        //根据小节id获取视频id，再删除
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();

        //数据效验
        if (!StringUtils.isEmpty(videoSourceId)) {
            System.out.println("程序执行到这");
            CommonResult result = vodClient.removeVideo(videoSourceId);
            System.out.println(result.getCode());
            if(result.getCode()==20001){
                throw new GuliException(20001,"删除视频失败");
            }
            System.out.println("程序执行到这222");
        }
        boolean remove = eduVideoService.removeById(id);//删除小节

        return remove?CommonResult.ok():CommonResult.error();
    }

    //修改小节
    @PostMapping("editVideo")
    public CommonResult editVideo(@RequestBody EduVideo eduVideo){
        boolean update = eduVideoService.updateById(eduVideo);
        return update?CommonResult.ok():CommonResult.error();
    }




    //根据小节id查询小节，铺垫修改小节的模态窗口
    @GetMapping("queryVideoById/{id}")
    public CommonResult queryVideoById(@PathVariable("id")String id){
        EduVideo eduVideo = eduVideoService.getById(id);
        return CommonResult.ok().data("eduVideo",eduVideo);
    }

}

